package com.example.demo.t2;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class T2_10 {

    public static void main(String[] args) throws Exception {
        Random r = new Random();
        long t1=0;
        long t2=0;

////        FileOutputStream fout = new FileOutputStream("word.txt");
//        BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream("word2.txt"));
//        t1 = System.currentTimeMillis();
//        for(int i=0; i<100_000_000; i++){
//            for(int j=0; j<5; j++){
//                fout.write(97 + r.nextInt(5));
//            }
//        }
//        t2 = System.currentTimeMillis();
//        System.out.println(t2 - t1);
//        fout.close();

//        FileInputStream fr = new FileInputStream("word2.txt");
        BufferedInputStream fr = new BufferedInputStream(new FileInputStream("word2.txt"));
        t1 = System.currentTimeMillis();
        var bytes = new byte[8192];
        while ( (fr.read(bytes))!= -1){
        }
        t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
        fr.close();

        FileChannel fc = new FileInputStream("word2.txt").getChannel();
        ByteBuffer buff = ByteBuffer.allocate(8192);
        t1 = System.currentTimeMillis();
        while ((fc.read(buff)) != -1) {
            buff.flip();
            // 读取buffer
//            System.out.println(new String(buff.array()));
            buff.clear();
        }
        t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
        fc.close();

        // 异步读取
        AsynchronousFileChannel afc = AsynchronousFileChannel.open(Path.of("word2.txt"), StandardOpenOption.READ);
        t1 = System.currentTimeMillis();

        var buff2 = ByteBuffer.allocate(8192);
        Future<Integer> operation = afc.read(buff2, 0);
        var numRead = operation.get();
        System.out.println(new String(buff2.array()));
        t2 = System.currentTimeMillis();
        System.out.println(t2 - t1);
        buff2.flip();
        var chars = new String(buff.array());
        buff2.clear();

        afc.close();


    }
}
